using System;
using System.Data.Common;
using System.Data.SqlClient;
using DataAssociations.Repository.Connection.RDBMSConnectionInterfaces;
using DataAssociations.Repository.Connection.RDBMSSchemaExplorer.Interfaces;
using DataAssociations.Repository.Connection.RDBMSSchemaExplorer.SchemaExplorer;
using DataAssociations.Repository.Connection.ValidationRules;
using DataAssociations.Repository.Queries;
using MySql.Data.MySqlClient;

namespace DataAssociations.Repository.Connection.RDBMSConnectionModels
{
    public class MySqlConnectionStringType : IConnectionStringType
    {
        private const int _connectionTimeoutDefalutValue = 10;
        private MySqlConnection _connection;
        private MySqlCommand _command;

        public int? ConnectionTimeout { get; set; }

        [NonEmptyStringValidation]
        public string Server { get; set; }

        [NonEmptyStringValidation]
        public string Database { get; set; }

        public string Password { get; set; }

        public string UserId { get; set; }

        public DbConnectionStringBuilder BuildConnectionString()
        {
            var builder = new MySqlConnectionStringBuilder();
            builder.ConnectionTimeout = (uint)(ConnectionTimeout ?? _connectionTimeoutDefalutValue);
            builder.Database = Database;
            builder.Server = Server;
            builder.PersistSecurityInfo = false;
            if (!string.IsNullOrWhiteSpace(Password))
                builder.Password = Password;
            if (!string.IsNullOrWhiteSpace(UserId))
                builder.UserID = UserId;
            return builder;
        }

        public string DataBaseManagementSystemName
        {
            get { return "MySql Database"; }
        }

        public DbConnection DataConnection
        {
            get
            {
                _connection = new MySqlConnection(BuildConnectionString().ConnectionString);
                return _connection;
            }
        }

        public DbCommand GetDbCommand(string query)
        {
            _command = new MySqlCommand(query, _connection);
            return _command;
        }

        public DbDataReader DataReader
        {
            get { return _command.ExecuteReader(); }
        }


        public IRelationalSchemaExplorer GetSchemaExporter
        {
            get { return new MySqlRelationalSchemaExplorer(); }
        }

        public IDataRepository GetDataRepository
        {
            get { return new MySqlDataRepository(); }
        }
    }
}